import 'package:flutter/material.dart';

// 父widget
class ParentWidget extends StatefulWidget {
  ParentWidget({Key? key}) : super(key: key);

  @override
  State<ParentWidget> createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  // 父管理状态
  bool _active = false;
  // 父组件决定点击事件的处理
  void _handleChange(bool newValue) {
    setState(() {
      _active = newValue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return ChildWidget(
      active: _active,
      onChanged: _handleChange,
    );
  }
}

// 子widget
class ChildWidget extends StatelessWidget {
  final bool active;
  final ValueChanged<bool> onChanged;

  const ChildWidget({Key? key, this.active = false, required this.onChanged})
      : super(key: key);

  void _handle() {
    // 子组件通过回调的方式将状态传给父组件，由父组件管理
    onChanged(!active);
  }

  @override
  Widget build(BuildContext context) {
    // 点击的按钮
    return GestureDetector(
      onTap: _handle,
      child: Container(
        width: 80,
        height: 50,
        child: Center(
          child: Text(
            active ? 'Active' : 'Not Active',
            style: TextStyle(
              fontSize: 32,
              color: Colors.white,
            ),
          ),
        ),
        decoration: BoxDecoration(color: active ? Colors.green : Colors.grey),
      ),
    );
  }
}
